//
//  SGSEventDescriptionViewController.m
//  AgileNYC
//
//  Created by German on 31.07.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSEventDescriptionViewController.h"
#import "GSEvent.h"
#import "SGSModelsManager.h"
#import "SGSUtils.h"
#import "SGSAppDelegate.h"
#import "SGSDialogsManager.h"
#import "SGSAppConsts.h"
#import "SGSDelegatesManager.h"

@interface SGSEventDescriptionViewController ()

@end

@implementation SGSEventDescriptionViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
#if WHITE_BACKGROUND
    self.vwEventRating.backgroundColor = [UIColor whiteColor];
    self.vwCaption.backgroundColor = [UIColor whiteColor];
#endif
    GSEvent * currEvent = [SGSModelsManager sharedModelsManager].currentEvent;
    
    //[[SGSModelsManager sharedModelsManager] requestImageForEventByEvent:currEvent loadToImageView:self.imgEventPhoto];
    
    [self.spinnerPhoto startAnimating];
    
    [[SGSModelsManager sharedModelsManager] requestImageForEventByEvent:currEvent onComplete:^(BOOL result, UIImage *image) {
        self.imgEventPhoto.image = image;
        [self.spinnerPhoto stopAnimating];
    }];
    
    self.labEventTitle.text = currEvent.topic;
    self.labEventTime.text = currEvent.eventTimeRangeInString;
    self.labTrack.text = currEvent.room;
    self.labAuthor.text = currEvent.author;
    
    /*if((currEvent.author) && ([currEvent.author length]>0)) {
        self.labAuthor.hidden = NO;
        self.labAuthor.text = currEvent.author;
    } else {
        self.labAuthor.hidden = YES;
    }*/
    
    self.labEventTitle.textAlignment = NSTextAlignmentLeft;
    self.labEventTitle.lineBreakMode = NSLineBreakByWordWrapping;
    //self.labEventTitle.numberOfLines = 0;
    
    self.labEventDescription.text = currEvent.introduction;
    self.labAvgRating.text = [NSString stringWithFormat:@"Overall rating: %.1f", [currEvent.avgRating floatValue]];
    [self changeRatingStars:[currEvent.myRating integerValue]];
    
    [self loadSessionID];
    
    [self switchPanels:NO];
    [self alignCaptions];
    
    GSLog(GSLogInfo, @"Event completed: %u",[currEvent isEventCompleted]);
    GSLog(GSLogInfo, @"Event date: %@", [currEvent eventDateInString]);

    GSLog(GSLogEvent, @"----- SGSEventDescriptionViewController Did Load");
}

-(void) changeRatingStars:(NSInteger) raiting {
    [self.btnStar1 setImage:[UIImage imageNamed:@"star_empty_56.png"] forState:UIControlStateNormal];
    [self.btnStar2 setImage:[UIImage imageNamed:@"star_empty_56.png"] forState:UIControlStateNormal];
    [self.btnStar3 setImage:[UIImage imageNamed:@"star_empty_56.png"] forState:UIControlStateNormal];
    [self.btnStar4 setImage:[UIImage imageNamed:@"star_empty_56.png"] forState:UIControlStateNormal];
    [self.btnStar5 setImage:[UIImage imageNamed:@"star_empty_56.png"] forState:UIControlStateNormal];
    
    switch (raiting) {
        case 5:
            [self.btnStar5 setImage:[UIImage imageNamed:@"star_56.png"] forState:UIControlStateNormal];
        case 4:
            [self.btnStar4 setImage:[UIImage imageNamed:@"star_56.png"] forState:UIControlStateNormal];
        case 3:
            [self.btnStar3 setImage:[UIImage imageNamed:@"star_56.png"] forState:UIControlStateNormal];
        case 2:
            [self.btnStar2 setImage:[UIImage imageNamed:@"star_56.png"] forState:UIControlStateNormal];
        case 1:
            [self.btnStar1 setImage:[UIImage imageNamed:@"star_56.png"] forState:UIControlStateNormal];
        default:
            break;
    }
}

-(void) loadSessionID {
    NSString * sessionID = [[SGSModelsManager sharedModelsManager] currentUser].sessionID;
    
    if ((sessionID) && (![sessionID isEqualToString:@"0"]) && (![sessionID isEqualToString:@"(null)"])) {
        self.labSessionId.text = sessionID;
        self.labSessionId.hidden = NO;
        //self.btnConnect.hidden = NO;
    } else {
        self.labSessionId.hidden = YES;
        //self.btnConnect.hidden = YES;
    }
}

- (IBAction)onRatingStarClick:(UIButton *)sender {
 
    [self checkLoginAndSetRating:sender.tag andMakeCheckIn:nil];
    
}

- (IBAction)onCheckInButtonClick:(UIButton*)sender {
    
    BOOL isCheckIn = [sender.titleLabel.text isEqualToString:CheckIn_Button_Title];
    
    [self checkLoginAndSetRating:0 andMakeCheckIn:[NSNumber numberWithBool:isCheckIn]];
    
}

-(void) checkLoginAndSetRating:(NSInteger) rating andMakeCheckIn:(NSNumber*) checkIn {
    
    self.delayCheckIn = checkIn;
    self.delayRating = rating;
    
    if (![[SGSModelsManager sharedModelsManager] checkUserLogin]) {
        
        UIViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSLoginViewController"];
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        
        SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
        GSEvent * currEvent = modelsManager.currentEvent;
        
        if (self.delayRating>0) {
            [modelsManager rateEvent:currEvent rating:self.delayRating onComplete:^(BOOL result) {
                if (result) {
                    self.labAvgRating.text = [NSString stringWithFormat:@"Overall rating: %.1f", [currEvent.avgRating floatValue]];
                }
            }];
            
            [self changeRatingStars:self.delayRating];
            
            self.delayRating = 0;
        }
        
        if (self.delayCheckIn) {
            
            BOOL isCheckIn = [self.delayCheckIn boolValue];
            
            [modelsManager checkInOnEvent:currEvent checkIn:isCheckIn onComplete:^(BOOL result, NSString * errorMessage) {
                GSLog(GSLogInfo, @"Check in: %@", currEvent.isCheckIn);
                
                if (!result) {
                    [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:errorMessage onComplete:nil];
                }
                
            }];
            
            [self switchPanels:YES];
            
            self.delayCheckIn = nil;
        }
    }
    
}

- (IBAction)onConnectButtonClick:(UIButton *)sender {
    [[SGSDelegatesManager sharedDelegatesManager].currentEventsVC showConnectionDialog];
}

- (IBAction)onButtonBackClick:(UIButton *)sender {
   [self.navigationController popViewControllerAnimated:YES];
}

-(void) switchPanels:(BOOL) animation {
    GSEvent * currEvent = [SGSModelsManager sharedModelsManager].currentEvent;
    
    CGFloat animationDur = 0.0f;
    
    if (animation) {
        animationDur = 0.4f;
    }
    
    if (([currEvent isEventInProcess]) || ([currEvent isEventCompleted])) {
        self.btnStar1.enabled = self.btnStar2.enabled = self.btnStar3.enabled =
        self.btnStar4.enabled = self.btnStar5.enabled = YES;
        self.btnStar1.alpha = self.btnStar2.alpha = self.btnStar3.alpha = self.btnStar4.alpha = self.btnStar5.alpha = 1.0f;
    } else {
        self.btnStar1.enabled = self.btnStar2.enabled = self.btnStar3.enabled =
        self.btnStar4.enabled = self.btnStar5.enabled = NO;
        self.btnStar1.alpha = self.btnStar2.alpha = self.btnStar3.alpha = self.btnStar4.alpha = self.btnStar5.alpha = 0.3f;
    }
    
    self.btnCheckIn.hidden = NO;
    
    if ([currEvent isEventCompleted]) {
    
        self.btnCheckIn.hidden = YES;
        self.labAvgRating.hidden = NO;
        self.imgCheckIn.hidden = YES;

    } else if ([currEvent isEventInProcess]) {
        self.btnCheckIn.hidden = NO;
        self.imgCheckIn.hidden = NO;
        self.labAvgRating.hidden = YES;
    } else {
        self.btnCheckIn.hidden = NO;
        self.labAvgRating.hidden = YES;
        self.imgCheckIn.hidden = NO;
    }
    
    if ([currEvent.isCheckIn boolValue]) {
        
        [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
        
        GSLog(GSLogInfo, @"self.btnCheckIn.center.x: %f", self.btnCheckIn.center.x);
        GSLog(GSLogInfo, @"self.vwEventRating.frame.size.width: %f", self.vwEventRating.frame.size.width);
        
        CGFloat width = self.vwEventRating.frame.size.height * 2.3;
        //CGFloat centerX = self.vwEventRating.frame.size.width - (self.btnCheckIn.frame.size.width) + 5;
        
        [UIView animateWithDuration:animationDur
                              delay:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             
                             self.btnCheckIn.frame = CGRectMake(self.btnCheckIn.frame.origin.x,
                                                                self.btnCheckIn.frame.origin.y,
                                                                width,
                                                                self.btnCheckIn.frame.size.height);

                             //self.btnCheckIn.center = CGPointMake(centerX,self.btnCheckIn.center.y);
                             
                             [self.btnCheckIn setTitle:Undo_Button_Title forState:UIControlStateNormal];
                             
                             self.btnCheckIn.backgroundColor = [UIColor clearColor];
                             [self.btnCheckIn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                             
                             self.imgCheckIn.alpha = 255.0f;
                         }
                         completion:^(BOOL finished){
                             [[UIApplication sharedApplication]endIgnoringInteractionEvents];
                         }];
        
        GSLog(GSLogInfo, @"[switchPanels] Check in");
        
    } else {
        
        CGFloat width = self.vwEventRating.frame.size.height * 2.3;
        //CGFloat centerX = self.vwEventRating.frame.size.width * 0.809375;
        //CGFloat centerX = self.vwEventRating.frame.size.width - (self.btnCheckIn.frame.size.width) - 5;
        
        GSLog(GSLogInfo, @"self.btnCheckIn.center.x: %f", self.btnCheckIn.center.x);
        GSLog(GSLogInfo, @"self.vwEventRating.frame.size.width: %f", self.vwEventRating.frame.size.width);
        
        [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
        
        [UIView animateWithDuration:animationDur
                              delay:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             self.imgCheckIn.alpha = 0.0f;
                             
                             //self.btnCheckIn.center = CGPointMake(centerX,self.btnCheckIn.center.y);
                             
                             self.btnCheckIn.frame = CGRectMake(self.btnCheckIn.frame.origin.x,
                                                                self.btnCheckIn.frame.origin.y,
                                                                width,
                                                                self.btnCheckIn.frame.size.height);
                             
                             [self.btnCheckIn setTitle:CheckIn_Button_Title forState:UIControlStateNormal];
                             
                             self.btnCheckIn.backgroundColor = COLOR_MAIN_BLUE;
                             [self.btnCheckIn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                         }
                         completion:^(BOOL finished){
                             [[UIApplication sharedApplication]endIgnoringInteractionEvents];
                         }];
        
        GSLog(GSLogInfo, @"[switchPanels] Cancel check in");
    }
    
}

#pragma mark - Align functions

-(void) alignCaptions {
    CGFloat sizeBetweenLabels = 6.0f;
    CGSize eventTitleLabelSize;
    CGSize authorLabelSize;
    CGSize trackLabelSize;
    CGFloat positionY;
    
    if ([[self.labEventTitle.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        eventTitleLabelSize = CGSizeMake(0, 0);
    } else {
        eventTitleLabelSize = labelSize(self.labEventTitle, self.labEventTitle.frame.size.width, self.labEventTitle.frame.size.height);
    }
    
    if ([[self.labAuthor.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        authorLabelSize = CGSizeMake(0, 0);
    } else {
        authorLabelSize = labelSize(self.labAuthor, self.labAuthor.frame.size.width, self.labAuthor.frame.size.height);
    }
    
    if ([[self.labTrack.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        trackLabelSize = CGSizeMake(0, 0);
    } else {
        trackLabelSize = labelSize(self.labTrack, self.labTrack.frame.size.width, self.labTrack.frame.size.height);
    }
    
    CGFloat heightToBound = self.imgEventPhoto.frame.size.height;
    
    // Calculate total height of all labels
    CGFloat totalLabelsHeight = eventTitleLabelSize.height;
    
    if (authorLabelSize.height>0) totalLabelsHeight += sizeBetweenLabels;
    
    totalLabelsHeight += authorLabelSize.height;
    
    if (trackLabelSize.height>0) totalLabelsHeight += sizeBetweenLabels;
    
    totalLabelsHeight += trackLabelSize.height;
    
    // Try to align label and image
    
    if (totalLabelsHeight>heightToBound) { //Выравниваем лейблы относительно материнской панели (помещаем лейблы в центр)

        positionY = ((self.vwCaption.frame.size.height-totalLabelsHeight) / 2);


    } else { //Выравниваем лейблы относительно фотографии
        
        positionY = self.imgEventPhoto.frame.origin.y + ((self.imgEventPhoto.frame.size.height-totalLabelsHeight) / 2);
        
    }
    
    //Сжимаем лейблы
    
    self.labEventTitle.frame = CGRectMake(self.labEventTitle.frame.origin.x,
                                          positionY,
                                          eventTitleLabelSize.width, eventTitleLabelSize.height);
    
    positionY += eventTitleLabelSize.height;
    
    if (authorLabelSize.height>0) positionY += sizeBetweenLabels;
    
    self.labAuthor.frame = CGRectMake(self.labAuthor.frame.origin.x,
                                      positionY,
                                      authorLabelSize.width, authorLabelSize.height);
    
    positionY += authorLabelSize.height;
    
    if (trackLabelSize.height>0) positionY += sizeBetweenLabels;
    
    self.labTrack.frame = CGRectMake(self.labTrack.frame.origin.x,
                                     positionY,
                                     trackLabelSize.width, trackLabelSize.height);
    
}

#pragma mark - System Functions

- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];}

@end
